/* eslint-disable @typescript-eslint/no-redeclare */
//React
import React, { useEffect, useState } from 'react';
import { Form, Input, Button, Card, Select, Upload, message } from 'antd';
import { PageContainer } from '@ant-design/pro-layout';
import {requestNetworking, requestFile} from '@/utils/request';
import { history } from 'umi';
import queryString from 'query-string';
import styles from '.staffAdd.less';

import { galleryInfo, galleryUpdate, galleryAdd, postFile, pictureAll, statusAll } from '../../services/gallery';

const Option = Select.Option;
const FormItem = Form.Item;

const formItemLayout = {
    labelCol: {
      xs: { span: 24 },
      sm: { span: 4 },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 20 },
    },
};



const Gallery = (props: any) => {
    const [form] = Form.useForm();
    const [content, setContent] = useState('');
    const [imageList, setImageList] = useState<any[]>([]);
    // 参数
    const [id, setId] = useState<any>(0);
    const [title, setTitle] = useState('');

    const [tag , setTag] = useState('');
    const [tagName,setTagName] = useState('');
    const [cover, setCover] = useState('');
    const [initContent, setInitContent] = useState('');
    const [fieldList, setFieldList] = useState([]);
    const [tagList, setTagList] = useState([]);
    const [createBackground,setCreateBackground]=useState('')
    const [writter, setWritter] = useState('');      
    const [loadings, setLoadings] = useState(true);
    const [name, setName] = useState(''); 
    const [sname, setSname] = useState(''); 
    const [status, setStatus] = useState('');
    const [statusName, setStatusName] = useState('');



    useEffect(() => {
      const search = queryString.parse(props.location.search);
      requestNetworking({}, pictureAll, (res: any)=>{
                const  options : any = [];
                res.dataList.map((item:any,index:any) => {
                  options.push(
                    <Option value={item.id} key={'type-field-'+index}>{item.tagName}</Option>
                  )
                });
              setFieldList(options);
      })
      requestNetworking({}, statusAll, (res: any)=>{
        const  options : any = [];
        res.dataList.map((item:any,index:any) => {
          options.push(
            <Option value={item.id} key={'type-field-'+index}>{item.statusName}</Option>
          )
        });
      setTagList(options);
    })
      if (search.id){
          const id = search.id;      
          requestNetworking({id}, galleryInfo, (data: any)=>{
              const  dataInfo = data.dataInfo;
            form.setFieldsValue({ tagName: dataInfo.tagName });
            form.setFieldsValue({ statusName: dataInfo.statusName});

              setId(id);                      
              setTitle(dataInfo.title);
              setWritter(dataInfo.writter);
              setCover(dataInfo.cover);
              setCreateBackground(dataInfo.createBackground);
              setStatus(dataInfo.status);
              setStatusName(dataInfo.status);
              if (dataInfo.status == 1) {
                setSname('未展出');
              } if(dataInfo.status == 2) {
                setSname('正在展出');
              } if (dataInfo.status == 3) {
                setSname('已展出')
              }
              setTag(dataInfo.tag);
              setTagName(dataInfo.tag);
            
              if(dataInfo.tag == 1) {
                 setName ('国画');
              }if(dataInfo.tag==2) {
                setName('水墨画');
              }if(dataInfo.tag == 3) {
                setName('素描');
              }if(dataInfo.tag == 4) {
                setName('油画');
              }if(dataInfo.tag == 5) {
                setName('漫画');
              }if(dataInfo.tag == 6) {
                setName('简笔画');
              }if(dataInfo.tag == 7) {
                setName('风景画');
            }
            setContent(dataInfo.content);
            setInitContent(dataInfo.content);
            setLoadings(false);
              const itemImg = {
                                uid: '-1',
                                name: 'image.png',
                                status: 'done',
                                url: data.dataInfo.cover,
                            }
                 setImageList([itemImg]);
                
          })            
      }else {
        setName('');
        setLoadings(false);
      }        
    }, [1])
  
    function inputChange(e: any){
        const  key = e.target.name;
        const  value = e.target.value;
        switch (key) {
            case 'title':
                setTitle(value);
                break;
            case 'writter':
              setWritter(value)
            default:
                break;
        }
    }
    function beforeUpload(e  : any) {
      const size = e.size;
      const name = e.name;
      const nameArray = name.split('.');let messageString = '请上传后缀是png、jpg和jpeg的文件';
        if (nameArray && nameArray.length > 1) {
          const itemName = nameArray[1];
          if (itemName == 'png' || itemName == 'jpg' || itemName == 'jpeg') {
            messageString = '';
          }
        }
        if (messageString.length !== 0) {
          message.warning(messageString);
          return;
        }
        if (size > 5 * 1024 * 1024) {
          message.warning('上传文件不能大于5M');
          return;
        }

        const params = {
            file: e
        }
        requestFile(params, postFile, function success(fileName:any){
            setCover(fileName)
            setImageList([
                {
                    uid: '-1',
                    name: 'image.png',
                    status: 'done',
                    url: global.getAction + fileName,
                }
            ])
        })
        return false;
    }

    function onChange(e: any){

    }

    function onRemove(){
        setImageList([]);
    }


    function selectField(e: any, option: any){
        setTag(e);
        setTagName(option.children)
  }
  function selectTag(e: any, option: any){
       setStatus(e);
       setStatusName(option.children)
}

    function sureBtn(){
        const param = {title, content,cover,writter,createBackground,tag,status};
        if (!title || !tag || !content){
            message.error('所有信息均为必填信息');
            return;
        }
        if (id){
            param['id'] = id;
            requestNetworking(param, galleryUpdate, ()=>{
                history.push('/gallery');
            })
        } else {
            requestNetworking(param, galleryAdd, ()=>{
                history.push('/gallery');
            })
        }
    }
  
    // 富文本
    let formItemArray = [];
    // 封面图
    const uploadButton = (
        <div>
            <div className="ant-upload-text">上传封面图</div>
        </div>
    );

    formItemArray.push(
        <FormItem
          key={'item-title'}
          {...formItemLayout}
          label={'标题'}
          name={'title'}
          rules={[{ required: true, message: '请输入标题' }]}
          initialValue={title}
        >
            <Input value={title} maxLength={50} name={'title'} onChange={inputChange} placeholder={'请输入标题'}/>
        </FormItem>,
    );
    
    formItemArray.push(
        <FormItem
        key={'item-type'}
        {...formItemLayout}
        label={'类别'}
        name={'tag'}
        rules={[{ required: true, message: '请选择类别'}]}
        >
        <Select
          placeholder = '请选择类别'
          style = {{ width: 200 }}
          size='middle'
          onSelect={(value, option) => selectField(value, option)}
          value={tagName}
          defaultValue={name}
        >
          {fieldList}
        </Select>
      </FormItem>
  )
   
  formItemArray.push(
    <FormItem
    key={'item-type'}
    {...formItemLayout}
    label={'状态'}
    name={'status'}
    rules={[{ required: true, message: '请选择状态'}]}
    >
    <Select
      placeholder = '请选择状态'
      style = {{ width: 200 }}
      size='middle'
      onSelect={(value, option) => selectTag(value, option)}
      value={statusName}
      defaultValue={sname}
    >
      {tagList}
    </Select>
  </FormItem>
)
    formItemArray.push(
        <FormItem
            key={'image-item-img'}
            {...formItemLayout}
            label={'封面图'}
            name={'cover'}
            rules={[{ required: true, message: '请选择上传封面图' }]}
            >
            <div>
                <Upload
                    name="avatar"
                    listType="picture-card"
                    className={styles.uploader}
                    accept=".jpg,.jpeg,.png"
                    beforeUpload={beforeUpload}
                    onRemove={onRemove}
                    onChange={onChange}
                    fileList={imageList}
                    >
                    {imageList.length >= 1 ? null : uploadButton}
                </Upload>
            </div>
        </FormItem>,
    );
    formItemArray.push(
      <FormItem
        key={'item-title'}
        {...formItemLayout}
        label={'作者'}
        name={'writter'}
        rules={[{ required: true, message: '请输入作者' }]}
        initialValue={writter}
      >
          <Input value={writter} maxLength={50} name={'writter'} onChange={inputChange} placeholder={'请输入作者'}/>
      </FormItem>,
  );
  formItemArray.push(
    <FormItem
      key={'item-title'}
      {...formItemLayout}
      label={'创作背景'}
      name={'createBackground'}
      rules={[{ required: true, message: '创作背景' }]}
      initialValue={createBackground}
    >
        <Input value={createBackground} maxLength={50} name={'createBackground'} onChange={inputChange} placeholder={'创作背景'}/>
    </FormItem>,
);
  

    const editorBraftProps = {
        getAction: global.getAction,
        content: initContent,
        callback: (content: string)=>{
            setContent(content);
        }
    };
    formItemArray.push(
        <div key={'EditorBraft'} title={'富文本'} className={styles.reactQuill}>
            <EditorBraft {...editorBraftProps} />
        </div>,
    );

  return (
    <PageContainer title={id ? '修改新闻资讯' : '添加新闻资讯'} content="">
      <Card bordered={false}>
      {loadings ?
            null
            :
        <div className={styles.add_div}>
            <Form form={form}>
                {formItemArray}
            </Form>
          <div className={styles.submit_div}>
            <Button type="primary" onClick={sureBtn}>
              确定
            </Button>
          </div>
        </div>
}
      </Card>
    </PageContainer>
  );
};

export default Gallery;



function pictureAll(arg0: {}, pictureAll: any, arg2: (res: any) => void) {
    throw new Error('Function not implemented.');
}

